// 连接蓝牙相关操作
import $store from '@/store/index'
let characteristics = []
class Connect {
	constructor(id) {
		this.deviceId = id
		this.mainUUID = $store.state['ble-info'].mainService
		this.nottifyUUID = $store.state['ble-info'].nottifyUUID
		this.writeUUID = $store.state['ble-info'].writeUUID
	}
	// 错误提示
	errMessage(code) {
		$store.commit('ble-info/BLE_ERR_TOAST', code)
	}
	// 获取服务
	getServices() {
		console.log('获取蓝牙服务')
		return new Promise((resolve, reject) => {
			uni.createBLEConnection({
				deviceId: this.deviceId,
				success: res => {
					setTimeout(() => {
						// 获取蓝牙设备所有服务
						// 经过反复测试该方法需要延迟900ms左右
						uni.getBLEDeviceServices({
							deviceId: this.deviceId,
							success: res => {
								resolve(res)
							}
						})
					}, 900)
				}
			})
		})
	}
	// 获取特征值
	getCharacteristicValue() {
		console.log('获取蓝牙特征值')
		return new Promise((resolve, reject) => {
			this.getServices().then(res => {
				const serviceList = res.services
				const idMaps = serviceList.map(item => item.uuid)
				if (!idMaps.includes(this.mainUUID)) {
					reject('未获取到设备主服务！')
				} else {
					uni.getBLEDeviceCharacteristics({
						deviceId: this.deviceId,
						serviceId: this.mainUUID,
						success: res => {
							characteristics = res.characteristics
							resolve(res.characteristics)
						}
					})
				}
			})
		})
	}
	// 根据获取的特征值设置uuid
	setUUID(type) {
		return new Promise((resolve, reject) => {
			let context = characteristics.filter(item => item.properties && item.properties[type])
			if(!context.length) {
				this.getCharacteristicValue().then(arr => {
					context = arr.filter(item => item.properties && item.properties[type])
					if(context.length) {
						resolve(context[0].uuid)
					} else {
						reject()
					}
				})
			} else {
				resolve(context[0].uuid)
			}
		})
	}
	// 获取写入特征值
	// 返回值，写入的uuid
	getWriteValue() {
		console.log('写入数据准备')
		return new Promise((resolve, reject) => {
			this.setUUID('write', characteristics).then(res => {
				resolve(res)
			})
		})
	}
	// 获取广播特征值
	// 返回值，广播uuid
	getNotifyValue() {
		console.log('开启广播')
		return new Promise((resolve, reject) => {
			this.setUUID('notify', characteristics).then(res => {
				resolve(res)
			})
		})
	}
	/**
	 * 向蓝牙设备写入数据
	 * @param {Buffer} value 写入的值
	 * @param {String} uuid 写入的uuid
	 */
	writeValue(value, uuid) {
		return new Promise((resolve, reject) => {
			if(uuid != this.writeUUID) {
				this.errMessage('特征值不正确！')
				reject()
			} else if(!value) {
				this.errMessage('写入值不正确！')
				reject()
			} else {
				uni.writeBLECharacteristicValue({
					deviceId: this.deviceId,
					serviceId: this.mainUUID,
					characteristicId: this.writeUUID,
					value: value,
					success: res => {
						resolve(res)
					},
					fail: err => {
						this.errMessage(err.errCode)
						reject()
					}
				}) 
			}
		})
	}
	/**
	 * 开启广播
	 * @param {String} uuid 广播uuid 
	 */
	openNotify(uuid) {
		return new Promise((resolve, reject) => {
			if(uuid != this.nottifyUUID) {
				errMessage('特征值不正确！')
				reject()
			} else {
				uni.notifyBLECharacteristicValueChange({
					deviceId: this.deviceId,
					serviceId: this.mainUUID,
					characteristicId: this.nottifyUUID,
					state: true,
					success: res => {
						resolve(res)
					},
					fail: err => {
						this.errMessage(err.errCode)
						reject()
					}
				})
			}
		})
	}
	// 关闭广播
	clostNotify() {

	}
	// 断开
	disconnect() {

	}
}

export default Connect